package com.service.impl;

import com.dao.PermissionResourceMapper;
import com.dao.PermissionSysUserRoleMapper;
import com.dao.SysUserMapper;
import com.exception.BusinessException;
import com.exception.LoginTimeOutException;
import com.exception.ServiceRuntimeException;
import com.model.PermissionResource;
import com.model.SysUser;
import com.po.PermissionResourcePO;
import com.service.PermissionResourceService;
import com.utils.BuildTree;
import com.utils.SessionUtil;
import com.utils.Tree;
import com.vo.PermissionResourceVO;

import com.vo.ResourceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.testng.collections.Lists;

import java.util.*;

/**
 * @Author: chihaojie
 * @Date: 2019/5/29 16:18
 * @Version 1.0
 * @Note
 */

@Slf4j
@Service
public class PermissionResourceServiceImpl implements PermissionResourceService {


    @Autowired
    private PermissionResourceMapper permissionResourceMapper;

    @Autowired
    private SysUserMapper   sysUserMapper;

    @Autowired
    private PermissionSysUserRoleMapper  sysUserRoleMapper;

    public static  final  List<String> asList=Lists.newArrayList( Arrays.asList("21","23","26","45","7","30","43","31","33","10","11","54"));


    @Override
    public PermissionResourceVO save(PermissionResourcePO permissionResourcePO) {
        Assert.notNull(permissionResourcePO,"参数不能为空");
        PermissionResourceVO  result=new  PermissionResourceVO();
        PermissionResource   resource   =  new PermissionResource();
        Date    now  = new Date();
        BeanUtils.copyProperties(permissionResourcePO,resource);
        //判断资源的等级
        if(permissionResourcePO.getLevel().equals(1)){
            //如果是一级资源的话，就把父级ID设置为-1
            resource.setParentId(-1L);
            resource.setStatus((byte)1);
        }
        //设置时间
        resource.setCreateTime(now);
        permissionResourceMapper.insert(resource);
        BeanUtils.copyProperties(resource,result);
        return result;
    }


    @Override
    public PermissionResourceVO edit(PermissionResourcePO permissionResourcePO) {
        Assert.notNull(permissionResourcePO,"参数不能为空");
        Assert.notNull(permissionResourcePO.getId(),"id不能为空");
        PermissionResourceVO  result=new  PermissionResourceVO();
        //查询
        PermissionResource resource = permissionResourceMapper.selectByPrimaryKey(permissionResourcePO.getId());
        if(ObjectUtils.isEmpty(resource)){
            throw new ServiceRuntimeException("该记录不存在!");
        }
        resource.setName(permissionResourcePO.getName());
        resource.setParentId(permissionResourcePO.getParentId());
        resource.setComment(permissionResourcePO.getComment());
        resource.setLevel(permissionResourcePO.getLevel());
        resource.setMethod(permissionResourcePO.getMethod());
        resource.setUpdated(permissionResourcePO.getUpdated());
        resource.setUpdateTime(new Date());
        permissionResourceMapper.updateByPrimaryKey(resource);
        BeanUtils.copyProperties(resource,result);
        return result;
    }

    @Override
    public Object remove(Long id) {
        Assert.notNull(id,"id不能为空");
        //查询
        PermissionResource resource = permissionResourceMapper.selectByPrimaryKey(id);
        if(ObjectUtils.isEmpty(resource)){
            throw new ServiceRuntimeException("该记录不存在!");
        }
        permissionResourceMapper.deleteByPrimaryKey(id);
        return null;
    }

    /**
     * 获取属性资源
     * @param resourceId
     * @return
     */
    @Override
    public List<Tree<ResourceVO>> treeByResourceId(Long resourceId) {
        //查询所有的资源集合
        List<ResourceVO> resources =   permissionResourceMapper.selectResourceList();
        //创建一个树集合
        List<Tree<ResourceVO>> trees = new ArrayList<Tree<ResourceVO>>(resources.size());
        //遍历资源集合
        for (ResourceVO  c: resources) {
            Tree<ResourceVO> tree = new Tree<ResourceVO>(c.getId(), c.getName(), c.getParentId());
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("level", c.getLevel());
            attributes.put("status", c.getStatus());
            tree.setAttributes(attributes);
            tree.setChecked(true);
            trees.add(tree);
        }
        return BuildTree.build(trees).getChildrenNode();
    }


    /**
     *
     * @return
     */
    @Override
    public List<ResourceVO> getTopResourceNodeList() {
        //查询所有的顶级目录
        List<ResourceVO>  list= permissionResourceMapper.selectTopResourceNodeList();
        if(ObjectUtils.isEmpty(list)){
            list= Lists.newArrayList();
        }
        return list;
    }

    @Override
    public List<ResourceVO> getSubResourceNodeList(String resourceId) {
        Long currentUserId =SessionUtil.getCurrentUserId();
        System.out.println("获取角色列表:  当前用户的id是:   "+currentUserId);
        if(ObjectUtils.isEmpty(currentUserId)){
            throw  new LoginTimeOutException("登录超时,请重新登录");
        }
        SysUser user = sysUserMapper.selectByPrimaryKey(currentUserId);
        List<Long> roles = sysUserRoleMapper.selectRoleIdListByAccountId(user.getId());
        if (roles.size() ==0){
            throw  new BusinessException(500,"账号角色异常");
        }
        List<ResourceVO> resources =   permissionResourceMapper.selectResourceListByRoleId(roles.get(0));
        ResourceVO resourceVO=permissionResourceMapper.selectResourceIdByName(resourceId.trim());
        if(ObjectUtils.isEmpty(resourceVO)){
            throw  new BusinessException(500,"没有当前资源");
        }
        //查询所有的顶级目录
        List<ResourceVO> resultList=Lists.newArrayList();
        Long  topResourceId=resourceVO.getId();
        List<ResourceVO>  list= permissionResourceMapper.selectSubResourceNodeList(topResourceId);
        if(ObjectUtils.isEmpty(list)){
            list= Lists.newArrayList();
        }else{
            for (ResourceVO  sub:list) {
                if(!ObjectUtils.isEmpty(resources)){
                    for (ResourceVO mine: resources) {
                        if(sub.getId().equals(mine.getId())){
                            resultList.add(sub);
                        }
                    }
                }

            }
        }
        if(user.getUserType().equals(1)){
            //show字段处理
            for (ResourceVO  resource:resultList) {
                if(asList.contains(resource.getId()+"")){
                    resource.setIsShow(false);
                    resource.setShow(false);
                }
            }
        }
        return resultList;
    }

    @Override
    public List<Tree<ResourceVO>> treeResource() {
        Long currentUserId = SessionUtil.getCurrentUserId();
        System.out.println("获取角色列表:  当前用户的id是:   "+currentUserId);
        if(ObjectUtils.isEmpty(currentUserId)){
            throw  new LoginTimeOutException("登录超时,请重新登录");
        }
        SysUser user = sysUserMapper.selectByPrimaryKey(currentUserId);
        // List<PermissionRoleVO> roleVOList = sysUserRoleMapper.selectRoleListByUserId(user.getId());
        List<Long> roles = sysUserRoleMapper.selectRoleIdListByAccountId(user.getId());
        //查询所有的资源集合
        List<ResourceVO> resources =   permissionResourceMapper.selectResourceListByRoleId(roles.get(0));
        if(user.getUserType().equals(1)){
            //如果是root用户则查询所有的资源
            resources=permissionResourceMapper.selectResourceList();
        }
        //创建一个树集合
        List<Tree<ResourceVO>> trees = new ArrayList<Tree<ResourceVO>>(resources.size());
        //遍历资源集合
        for (ResourceVO  c: resources) {
            Tree<ResourceVO> tree = new Tree<ResourceVO>(c.getId(), c.getName(), c.getParentId());
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("level", c.getLevel());
            attributes.put("status", c.getStatus());
            tree.setName(c.getName());
            tree.setParentId(c.getParentId()+"");
            tree.setComment(c.getComment());
            tree.setUrl(c.getUrl());
            tree.setLevel(c.getLevel()+"");
            tree.setMethod(c.getMethod());
            tree.setAttributes(attributes);
            tree.setChecked(true);
            trees.add(tree);
        }
        return BuildTree.build(trees).getChildrenNode();
    }
}
